package ink.lovejinhu.leetcode;

import ink.lovejinhu.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jinhu
 * created 2021-07-22 14:03
 */
public class Solution_0530 {
    public static void main(String[] args) {
        TreeNode node01 = new TreeNode(4);
        TreeNode node02 = new TreeNode(2);
        TreeNode node03 = new TreeNode(6);
        TreeNode node04 = new TreeNode(1);
        TreeNode node05 = new TreeNode(3);
        node01.left = node02;
        node01.right = node03;
        node02.left = node04;
        node02.right = node05;
        Solution_0530 solution_0530 = new Solution_0530();
        solution_0530.getMinimumDifference(node01);
        System.out.println(solution_0530.getMinimumDifference(node01));


    }

    /**
     * @param root
     * @return
     */
    public int getMinimumDifference(TreeNode root) {
        int[] res = new int[1];
        res[0] = Integer.MAX_VALUE;
        this.dfs(root, res);
        return res[0];
    }

    public void dfs(TreeNode root, int[] res) {
        if (root == null) return;
        if (root.left != null) {
            res[0] = Math.min(res[0], Math.abs(root.val - root.left.val));
        }
        if (root.right != null) {
            res[0] = Math.min(res[0], Math.abs(root.val - root.right.val));
        }
        dfs(root.left, res);
        dfs(root.right, res);
    }

    public List<Integer> temp = new ArrayList<Integer>();

    public int getMinimumDifference01(TreeNode root) {
        this.dfs01(root);
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < temp.size() - 1; i++) {
            if (min > Math.abs(temp.get(i) - temp.get(i + 1))) {
                min = Math.abs(temp.get(i) - temp.get(i + 1));
            }
        }
        return min;
    }

    public void dfs01(TreeNode root) {
        if (root == null) return;
        dfs01(root.left);
        temp.add(root.val);
        dfs01(root.right);
    }
}
